package com.letv.android.client.episode.fragment;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.ledim.activity.RoomActivity;
import com.ledim.adapter.ChatAdapter;
import com.ledim.adapter.EmojiPageSetAdapter;
import com.ledim.adapter.YanPagerAdapter;
import com.ledim.bean.ChatRoomBean;
import com.ledim.bean.ChatRoomShareData;
import com.ledim.bean.ExpressionPackageBean;
import com.ledim.bean.LedimChatBean;
import com.ledim.bean.LedimChatMsgBean;
import com.ledim.bean.LedimChatUserBean;
import com.ledim.bean.LedimJoinAckBean;
import com.ledim.bean.LedimKickOffBean;
import com.ledim.bean.LedimRoomStatus;
import com.ledim.bean.LedimRoomUsersInfoBean;
import com.ledim.bean.LedimUserBean;
import com.ledim.bean.LedimWatchUserBean;
import com.ledim.bean.LedimWatchUserResponse;
import com.ledim.bean.RoomInfoResponse;
import com.ledim.bean.RoomNoticeBean;
import com.ledim.bean.RoomPlaylistResponse;
import com.ledim.bean.UploadRoomNoticeBean;
import com.ledim.bean.base.BaseResultDataInfo;
import com.ledim.chat.ChatCallback;
import com.ledim.chat.ChatController;
import com.ledim.chat.model.ChatEntity;
import com.ledim.chat.model.MessageHeader;
import com.ledim.fragment.CommonDialogFragment;
import com.ledim.itf.LedimDialogClickListner;
import com.ledim.itf.YanViewEventObserver;
import com.ledim.ledimview.YanInputBaseView;
import com.ledim.service.ApiService;
import com.ledim.service.LedimApiServiceFactory;
import com.ledim.service.LedimApiServiceUtils;
import com.ledim.service.LedimHttpObserver;
import com.ledim.service.coverter.LedimGsonConverterFactory;
import com.ledim.share.ShareDialogFragment;
import com.ledim.utils.ConstantUtil;
import com.ledim.utils.DensityUtil;
import com.ledim.utils.EmotionHelper;
import com.ledim.utils.FrescoUtil;
import com.ledim.utils.LedimBaseUtils;
import com.ledim.utils.LedimFunctionUtils;
import com.ledim.utils.LedimNetWorkUtils;
import com.ledim.utils.LedimRecordPlayer;
import com.ledim.utils.LedimScreenShotUtils;
import com.ledim.utils.LedimSpUtils;
import com.ledim.utils.LogUtil;
import com.ledim.utils.ToastUtil;
import com.ledim.widget.view.AudioRecordButton;
import com.ledim.widget.view.KeyboardLayout;
import com.ledim.widget.view.LoadingBar;
import com.ledim.widget.view.PeriscopeLayout;
import com.ledim.widget.viewpagerindicator.CirclePageIndicator;
import com.letv.android.client.activity.AlbumPlayRoomActivity;
import com.letv.android.client.album.controller.AlbumRoomEmojController;
import com.letv.android.client.constant.FragmentConstant;
import com.letv.android.client.fragment.LetvBaseFragment;
import com.letv.android.young.client.R;
import com.letv.core.constant.PlayConstant;
import com.letv.core.utils.UIsUtils;
import java.io.File;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import org.greenrobot.eventbus.EventBus;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 放映室聊天页面
 */
public class TabsRoomFragment extends LetvBaseFragment
        implements View.OnClickListener, EmojiPageSetAdapter.OnClickDimIconListner,
                   AlbumRoomEmojController.EmjDataObserve, YanViewEventObserver {

    private static int TIME = 30 * 1000;
    private Handler mHandler;
    private Timer mTimer;
    private HeartTimerTask mHeartTimerTask;

    private View mRootLayout;
    private KeyboardLayout mChatView;
    private PeriscopeLayout mPeriscopeLayout;
    private ListView mListView;
    private TextView mChatViewCount;
    private ImageView mChatBearGoldBg;
    private ImageView mChatBearGold;
    private TextView mChatGoldCount;

    private LinearLayout mChatInputEditLayout;
    private EditText mChatInputEdit, myroom_input_edit;
    private TextView mChatInputCount;
    private ImageView mChatCheck;
    private ImageView iv_room_vedioinfo;//聊天室聚集信息
    private ImageView iv_sound;
    private ImageView iv_palyrecord_sound;
    private View myroom_input_layout, myroom_input_edit_layout;
    private TextView tv_notice_msg;//公告文案信息
    private TextView myroom_input_count;//公告字数
    private View ll_roomnotice_sound;//公告语音信息

    private LinearLayout mChatInputLayout;
    private TextView mChatInput;
    private ImageView mChatEmoji;
    private LinearLayout mYanView;
    private ViewPager mYanViewPager;
    private CirclePageIndicator mYanIndicator;
    private TextView mYanSend;

    private ArrayList<View> mViewPagerList = new ArrayList<View>();
    private YanPagerAdapter mYanPagerAdapter;

    private ChatRoomBean mRoom;
    private boolean mIsMe;
    private ChatAdapter mChatAdapter;

    private WeakReference<AlbumPlayRoomActivity> mActivity;

    private ArrayList<LedimChatMsgBean> mChatList = new ArrayList<LedimChatMsgBean>();

    private int mRoomUserCount = 0; // 当前放映厅观看人数

    private final int MSG_SEND_GOLD = 1;
    private int mSendCount;

    private Bitmap mBitmap;
    private AnimationDrawable mAnimationDrawable = null;

    private int mGoldCount;
    private View fl_room_gold;

    private Subscription subscription;//分享请求
    private Subscription uploadRecordSubscription;//上传语音公告
    private Subscription uploadTextSubscription;// 上传文字公告
    private Subscription getRoomNoticeSubscription;//获取房间公告 用于非房主
    private Subscription getWatchUserSubscription;//获取观影人员
    private AudioRecordButton recordButton;
    private final int CHAT_INPUT_MODE = 0;//聊天输入type
    private final int NOTICE_INPUT_MODE = 1;//公告输入type
    private int mInputMode = CHAT_INPUT_MODE; //输入模式 默认是聊天输入type

    private final int NOTICE_TEXT_TYPE = 1;//文案公告
    private final int NOTICE_RECORD_TYPE = 2;//语音公告
    private int mRoomNoticeType = NOTICE_TEXT_TYPE;//房间公告类型
    private String mRoomNotice; // 根据文案type设置
    private LedimRecordPlayer mLedimRecordPlayer;
    private LinearLayout ll_watch_user;

    private RadioGroup mkeyboradIndexRadioGroup;
    private ImageView iv_yan;
    private SimpleDraweeView iv_yuc_bg;
    private ViewPager mImageViewpager;
    private String shareUrl;
    private String sharePath;
    private LoadingBar mLoadingBar;
    private CommonDialogFragment mSilentDialog;//禁言提示dialog
    private CommonDialogFragment mKickOffDialog;//被踢出dialog

    private CommonDialogFragment mPlayEndDialog;
    private boolean mForBiddenSpeak;
    private LedimChatBean mChatBean;
    private ChatController mChatController;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mIsMe = bundle.getBoolean(PlayConstant.IS_ME, false);
            mRoom = (ChatRoomBean) bundle.getSerializable(PlayConstant.ROOM);
            mRoomNotice = mRoom.announcement;
            mRoomNoticeType = mRoom.announcement_type;
        }

    }

    public static TabsRoomFragment getInstance(boolean isMe, ChatRoomBean room) {
        Bundle bundle = new Bundle();
        bundle.putBoolean(PlayConstant.IS_ME, isMe);
        bundle.putSerializable(PlayConstant.ROOM, room);
        TabsRoomFragment roomFragment = new TabsRoomFragment();
        roomFragment.setArguments(bundle);
        return roomFragment;
    }

    public void setActivity(Activity activity) {
        mActivity = new WeakReference<AlbumPlayRoomActivity>((AlbumPlayRoomActivity) activity);

    }

    /**
     * 初始化房间公告UI
     */
    private void initRoomNoticeUi() {
        //// TODO: 16/7/21  服务器说暂时无法将notice完全置成空
        if (!TextUtils.isEmpty(mRoomNotice) && !mRoomNotice.equals("null")) {
            if (mRoomNoticeType == NOTICE_TEXT_TYPE) {
                tv_notice_msg.setVisibility(View.VISIBLE);
                ll_roomnotice_sound.setVisibility(View.GONE);
                tv_notice_msg.setText(mRoomNotice);
            } else if (mRoomNoticeType == NOTICE_RECORD_TYPE) {
                tv_notice_msg.setVisibility(View.GONE);
                ll_roomnotice_sound.setVisibility(View.VISIBLE);
            }
        } else {
            if (mRoomNoticeType == NOTICE_TEXT_TYPE || mRoomNoticeType == 0) {
                tv_notice_msg.setVisibility(View.VISIBLE);
                ll_roomnotice_sound.setVisibility(View.GONE);
                if (mIsMe) {
                    tv_notice_msg.setText(R.string.room_notice_me);
                } else {
                    tv_notice_msg.setText(R.string.room_notice_others);
                }
            }
        }

    }

    private void initChatController() {
        mChatController = new ChatController(new ChatCallback() {
            @Override
            public void onReceiveMessage(ChatEntity message) {
                handlerChatMsg(message);
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mRootLayout = inflater.inflate(R.layout.letv_detailplay_room_view, null);
        mChatView = (KeyboardLayout) mRootLayout.findViewById(R.id.room_chat_view);
        mPeriscopeLayout = (PeriscopeLayout) mActivity.get().findViewById(R.id.room_chat_periscope);
        mListView = (ListView) mRootLayout.findViewById(R.id.room_chat_list);
        mChatViewCount = (TextView) mRootLayout.findViewById(R.id.room_chat_view_count);
        mChatBearGold = (ImageView) mRootLayout.findViewById(R.id.room_chat_bear_gold);

        mChatGoldCount = (TextView) mRootLayout.findViewById(R.id.room_chat_gold_count);
        if (mIsMe) {
            mChatGoldCount.setVisibility(View.GONE);
        } else {
            mChatGoldCount.setVisibility(View.VISIBLE);
        }
        mChatBearGoldBg = (ImageView) mRootLayout.findViewById(R.id.room_chat_bear_gold_bg);

        mChatInputEditLayout =
                (LinearLayout) mRootLayout.findViewById(R.id.room_chat_input_edit_layout);
        mChatInputEdit = (EditText) mRootLayout.findViewById(R.id.room_chat_input_edit);
        mChatInputCount = (TextView) mRootLayout.findViewById(R.id.room_chat_input_count);
        mChatCheck = (ImageView) mRootLayout.findViewById(R.id.room_chat_input_check);
        mChatInputLayout = (LinearLayout) mRootLayout.findViewById(R.id.room_chat_input_layout);

        mChatInput = (TextView) mRootLayout.findViewById(R.id.room_chat_input);
        mChatEmoji = (ImageView) mRootLayout.findViewById(R.id.room_chat_emoji);
        iv_room_vedioinfo = (ImageView) mRootLayout.findViewById(R.id.iv_room_vedioinfo);
        mYanView = (LinearLayout) mRootLayout.findViewById(R.id.room_chat_input_yan_view);
        mYanViewPager = (ViewPager) mRootLayout.findViewById(R.id.room_chat_input_yan_viewpager);
        mYanIndicator =
                (CirclePageIndicator) mRootLayout.findViewById(R.id.room_chat_input_yan_indicator);
        mYanSend = (TextView) mRootLayout.findViewById(R.id.room_chat_yan_send);
        iv_sound = (ImageView) mRootLayout.findViewById(R.id.iv_sound);
        myroom_input_layout = mRootLayout.findViewById(R.id.myroom_input_layout);
        myroom_input_edit_layout = mRootLayout.findViewById(R.id.myroom_input_edit_layout);
        myroom_input_edit = (EditText) mRootLayout.findViewById(R.id.myroom_input_edit);
        tv_notice_msg = (TextView) mRootLayout.findViewById(R.id.tv_notice_msg);
        ll_roomnotice_sound = mRootLayout.findViewById(R.id.ll_roomnotice_sound);
        iv_palyrecord_sound = (ImageView) mRootLayout.findViewById(R.id.iv_palyrecord_sound);
        ll_roomnotice_sound.setOnClickListener(this);
        fl_room_gold = mRootLayout.findViewById(R.id.fl_room_gold);
        myroom_input_count = (TextView) mRootLayout.findViewById(R.id.myroom_input_count);
        if (!mIsMe) {
            fl_room_gold.setVisibility(View.VISIBLE);
        }

        //表情键盘下面的RadioGroup
        mkeyboradIndexRadioGroup =
                (RadioGroup) mRootLayout.findViewById(R.id.mp_emoji_single_keyborad_index);
        //颜色按钮
        iv_yan = (ImageView) mRootLayout.findViewById(R.id.iv_yan);
        //显示下载图片的viewpager
        mImageViewpager = (ViewPager) mRootLayout.findViewById(R.id.room_download_image_viewpage);

        ll_watch_user = (LinearLayout) mRootLayout.findViewById(R.id.ll_watch_user);
        initRoomNoticeUi();
        initChatController();
        if (mIsMe) {
            iv_room_vedioinfo.setImageResource(R.drawable.icon_setting);
            mChatBearGold.setImageResource(R.drawable.gold_black);
            iv_sound.setImageResource(R.drawable.icon_sound_enable);
            iv_sound.setOnClickListener(this);
        } else {
            mChatBearGold.setImageResource(R.drawable.bear_gold);
        }
        iv_yuc_bg = (SimpleDraweeView) mRootLayout.findViewById(R.id.iv_yuc_bg);
        if (mRoom.cosplay != 0 && !TextUtils.isEmpty(mRoom.background)) {
            FrescoUtil.loadUrl(mRoom.background, iv_yuc_bg);
        } else {
            iv_yuc_bg.setVisibility(View.GONE);
        }
        recordButton = (AudioRecordButton) mRootLayout.findViewById(R.id.recordButton);
        //对金币按钮进行判断,(房主没有金币按钮)
        if (mIsMe) {
            mChatBearGold.setVisibility(View.GONE);
            mActivity.get().getFullControllerFragment().setGoldInvisible();

        }
        mChatBearGoldBg.setImageResource(R.anim.round_animation);
        mAnimationDrawable = (AnimationDrawable) mChatBearGoldBg.getDrawable();
        mAnimationDrawable.setOneShot(false);
        YanInputBaseView view1 =
                (YanInputBaseView) View.inflate(getActivity(), R.layout.yan_view_1, null);
        YanInputBaseView view2 =
                (YanInputBaseView) View.inflate(getActivity(), R.layout.yan_view_2, null);
        YanInputBaseView view3 =
                (YanInputBaseView) View.inflate(getActivity(), R.layout.yan_view_3, null);
        view1.setObserver(this);
        view2.setObserver(this);
        view3.setObserver(this);
        mViewPagerList.add(view1);
        mViewPagerList.add(view2);
        mViewPagerList.add(view3);
        mYanPagerAdapter = new YanPagerAdapter(getActivity(), mViewPagerList);
        mYanViewPager.setAdapter(mYanPagerAdapter);
        mYanIndicator.setViewPager(mYanViewPager, 0);
        mYanIndicator.requestLayout();
        mRootLayout.findViewById(R.id.iv_room_share).setOnClickListener(this);
        iv_room_vedioinfo.setOnClickListener(this);
        mChatBearGold.setOnClickListener(this);
        mChatInput.setOnClickListener(this);
        mChatEmoji.setOnClickListener(this);
        mChatInputEdit.setOnClickListener(this);
        mChatCheck.setOnClickListener(this);
        mYanSend.setOnClickListener(this);
        mRootLayout.findViewById(R.id.iv_switchto_sound).setOnClickListener(this);
        mRootLayout.findViewById(R.id.iv_switchto_keyboard).setOnClickListener(this);
        mRootLayout.findViewById(R.id.iv_roomnoticeinput_cancle).setOnClickListener(this);
        mRootLayout.findViewById(R.id.iv_roomnoticerecord_cancel).setOnClickListener(this);
        mChatAdapter = new ChatAdapter(getActivity(), mChatList, mRoom, isWucRoom());
        mListView.setAdapter(mChatAdapter);
        if (!mIsMe) {
            playRecordNotice();
        }
        setListener();
        return mRootLayout;
    }

    private void setListener() {

        mYanViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                mYanIndicator.setCurrentItem(arg0);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });
        mChatInputEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mChatInputCount.setText((50 - s.length()) + "");
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        myroom_input_edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                myroom_input_count.setText((34 - s.length()) + "");
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        myroom_input_edit.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND) {
                    sendRoomTextNotice();
                    return true;
                }
                return false;
            }
        });
        //点击发送完成创建
        mChatInputEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND) {
                    if (!LedimSpUtils.isLogin()) {
                        LedimFunctionUtils.showLoginDialog(getActivity());
                    } else {
                        String inputStr = mChatInputEdit.getText().toString().trim();
                        if (inputStr.length() == 0) {
                            ToastUtil.toast("请输入评论内容");
                        } else {
                            sendRoomMsg(ConstantUtil.ChatType.text, inputStr);
                            localMessage(mRoom.roomId, ConstantUtil.ChatType.text, inputStr);
                            mChatInputEdit.setText("");
                            closeKeyBoard();
                        }
                    }
                    return true;
                }
                return false;
            }
        });

        mChatView.setOnkbdStateListener(new KeyboardLayout.onKybdsChangeListener() {
            @Override
            public void onKeyBoardStateChange(int state) {
                switch (state) {
                    case KeyboardLayout.KEYBOARD_STATE_HIDE:
                        if (mInputMode == CHAT_INPUT_MODE) {
                            mChatInputLayout.setVisibility(View.VISIBLE);
                            mChatInputEditLayout.setVisibility(View.GONE);
                        } else {
                            myroom_input_edit_layout.setVisibility(View.GONE);
                            myroom_input_layout.setVisibility(View.VISIBLE);
                        }

                        break;
                    case KeyboardLayout.KEYBOARD_STATE_SHOW:
                        if (mInputMode == CHAT_INPUT_MODE) {
                            mChatCheck.setImageResource(R.drawable.input_smiling_face);
                            mChatInputEditLayout.setVisibility(View.VISIBLE);
                            mChatInputLayout.setVisibility(View.GONE);
                            mYanView.setVisibility(View.GONE);
                            mChatInputEdit.setFocusable(true);
                            mChatInputEdit.setFocusableInTouchMode(true);
                            mChatInputEdit.requestFocus();
                            mListView.setSelection(mChatAdapter.getCount() - 1);
                        } else {
                            myroom_input_edit_layout.setVisibility(View.VISIBLE);
                            myroom_input_layout.setVisibility(View.GONE);
                            myroom_input_edit.setFocusable(true);
                            myroom_input_edit.setFocusableInTouchMode(true);
                            myroom_input_edit.requestFocus();
                        }

                        break;
                }
            }
        });
        mListView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                closeKeyBoard();
                if (mInputMode == CHAT_INPUT_MODE) {
                    mYanView.setVisibility(View.GONE);
                    mChatInputLayout.setVisibility(View.VISIBLE);
                    mChatInputEditLayout.setVisibility(View.GONE);
                } else {
                    myroom_input_edit_layout.setVisibility(View.GONE);
                    myroom_input_layout.setVisibility(View.VISIBLE);
                }

                return false;
            }
        });
        iv_yan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //mYanViewPager  mYanIndicator  mImageViewpager
                mImageViewpager.setVisibility(View.GONE);
                mYanViewPager.setVisibility(View.VISIBLE);

                mYanViewPager.setAdapter(mYanPagerAdapter);
                mYanIndicator.setViewPager(mYanViewPager, 0);
                mYanIndicator.requestLayout();

            }
        });
        recordButton.setAudioFinishRecorderListener(new AudioRecordButton.AudioFinishRecorderListener() {
            @Override
            public void onStart() {
                if (mActivity.get() != null) {
                    mActivity.get().setLockPortraitScreen(true);
                }
            }

            @Override
            public void onFinished(float seconds, String filePath) {
                sendRoomRecordNotice(filePath);
            }
        });
    }

    /**
     * @param filePath
     *         上传语音公告
     */
    private void sendRoomRecordNotice(final String filePath) {
        if (mActivity.get() != null) {
            mActivity.get().setLockPortraitScreen(false);
        }
        if (mLoadingBar == null) {
            mLoadingBar = new LoadingBar(getActivity());
        }
        mLoadingBar.show();
        //new LedimRecordPlayer().playUrl("http://g3.letv.cn/vod/v1/MjA2LzI2LzQ5L2Nsb3VkLXdlYi8wL2xjMDRfMjAxNjA2MjkvMTAzMjAwMTMzMi80MzFjZGNkNzFjMWE5NzU1Mjk0YTJkZGE1MDY4Njk3OC5tcDM=?b=1234&np=1");
        RequestBody photoRequestBody =
                RequestBody.create(MediaType.parse("media/mp3"), new File(filePath));
        uploadRecordSubscription = LedimApiServiceFactory.createService(ApiService.class)
                                                         .uploadRecordRoomNotice(mRoom.roomId, photoRequestBody, RequestBody
                                                                 .create(null,
                                                                         NOTICE_RECORD_TYPE + ""))
                                                         .observeOn(AndroidSchedulers.mainThread())
                                                         .subscribeOn(Schedulers.io())
                                                         .subscribe(new LedimHttpObserver<BaseResultDataInfo<UploadRoomNoticeBean>>() {
                                                             @Override
                                                             public void onError(Throwable e) {
                                                                 super.onError(e);
                                                                 mLoadingBar.dismiss();
                                                                 ToastUtil.toast(R.string.ledim_notice_retry);
                                                                 File recordFile =
                                                                         new File(filePath);
                                                                 if (recordFile.exists() &&
                                                                         recordFile.isFile()) {
                                                                     recordFile.delete();
                                                                 }
                                                             }

                                                             @Override
                                                             public void onNext(
                                                                     BaseResultDataInfo<UploadRoomNoticeBean> data) {
                                                                 // super.onNext(uploadRoomNoticeBeanBaseResultDataInfo);
                                                                 mLoadingBar.dismiss();
                                                                 if (data.success) {
                                                                     if (!TextUtils.isEmpty(data.data.announcement)) {
                                                                         myroom_input_layout.setVisibility(View.GONE);
                                                                         myroom_input_edit_layout.setVisibility(View.GONE);
                                                                         mChatInputLayout.setVisibility(View.VISIBLE);
                                                                         mInputMode =
                                                                                 CHAT_INPUT_MODE;
                                                                         closeKeyBoard();
                                                                         ToastUtil.toast(R.string.ledim_notice_ok);
                                                                         mRoomNoticeType =
                                                                                 NOTICE_RECORD_TYPE;
                                                                         mRoomNotice =
                                                                                 data.data.announcement;
                                                                         initRoomNoticeUi();
                                                                         File recordFile =
                                                                                 new File(filePath);
                                                                         if (recordFile.exists() &&
                                                                                 recordFile.isFile()) {
                                                                             recordFile.delete();
                                                                         }
                                                                     }
                                                                     LogUtil.e("record url==" +
                                                                             data.data.announcement);
                                                                 }
                                                             }

                                                         });
    }

    /**
     * 发送房间公告
     */
    private void sendRoomTextNotice() {
        if (!LedimSpUtils.isLogin()) {
            LedimFunctionUtils.showLoginDialog(getActivity());
        } else {
            String inputStr = myroom_input_edit.getText().toString().trim();
            if (inputStr.length() == 0) {
                ToastUtil.toast("请输入公告内容");
            } else {
                // 发送文字公告
                //mChatPostModel.send(TabsRoomFragment.this, ENUM_CHAT_TYPE.TEXT.value(), inputStr, mRoom.id, time, 0);
                //localMessage(mRoom.id, ENUM_CHAT_TYPE.TEXT.value(), inputStr, time);
                if (mLoadingBar == null) {
                    mLoadingBar = new LoadingBar(getActivity());
                }
                mLoadingBar.show();
                LogUtil.e("ccx upload userId=" + mRoom.roomId);
                uploadTextSubscription = LedimApiServiceFactory.createService(ApiService.class)
                                                               .uploadTextRoomNotice(mRoom.roomId, RequestBody
                                                                       .create(null, inputStr), RequestBody
                                                                       .create(null,
                                                                               NOTICE_TEXT_TYPE +
                                                                                       ""))
                                                               .observeOn(AndroidSchedulers.mainThread())
                                                               .subscribeOn(Schedulers.io())
                                                               .subscribe(new LedimHttpObserver<BaseResultDataInfo<UploadRoomNoticeBean>>() {
                                                                   @Override
                                                                   public void onError(
                                                                           Throwable e) {
                                                                       super.onError(e);
                                                                       mLoadingBar.dismiss();
                                                                       ToastUtil.toast(R.string.ledim_notice_retry);
                                                                   }

                                                                   @Override
                                                                   public void onNext(
                                                                           BaseResultDataInfo<UploadRoomNoticeBean> data) {

                                                                       // super.onNext(uploadRoomNoticeBeanBaseResultDataInfo);
                                                                       mLoadingBar.dismiss();
                                                                       if (data.success &&
                                                                               !TextUtils.isEmpty(data.data.announcement)) {
                                                                           myroom_input_layout.setVisibility(View.GONE);
                                                                           myroom_input_edit_layout.setVisibility(View.GONE);
                                                                           mChatInputLayout.setVisibility(View.VISIBLE);
                                                                           mInputMode =
                                                                                   CHAT_INPUT_MODE;
                                                                           closeKeyBoard();

                                                                           mRoomNoticeType =
                                                                                   NOTICE_TEXT_TYPE;
                                                                           mRoomNotice =
                                                                                   data.data.announcement;
                                                                           initRoomNoticeUi();
                                                                       }
                                                                   }

                                                                   @Override
                                                                   public void onCompleted() {
                                                                       super.onCompleted();
                                                                       mLoadingBar.dismiss();
                                                                   }
                                                               });
                myroom_input_edit.setText("");

            }
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.iv_room_share:
                share(true);
                break;
            case R.id.iv_room_vedioinfo:
                intent = new Intent(mContext, RoomActivity.class);
                intent.putExtra(RoomActivity.ROOM_ID, mRoom);
                intent.putExtra(RoomActivity.MY_ROOM_FLAG, mIsMe);
                mContext.startActivity(intent);
                break;
            case R.id.room_chat_bear_gold:
                if (!LedimSpUtils.isLogin()) {
                    LedimFunctionUtils.showLoginDialog(getActivity());

                } else {
                    sendGold(false);
                }
                break;
            case R.id.room_chat_input:
                if (!LedimSpUtils.isLogin()) {
                    LedimFunctionUtils.showLoginDialog(getActivity());
                } else {
                    showKeyBoard();
                }
                break;
            case R.id.room_chat_emoji:
                if (!LedimSpUtils.isLogin()) {
                    LedimFunctionUtils.showLoginDialog(getActivity());
                } else {
                    mChatCheck.setImageResource(R.drawable.keyboard);
                    mChatInputEdit.setFocusable(true);
                    mChatInputEdit.setFocusableInTouchMode(true);
                    mChatInputEdit.requestFocus();
                    mYanView.setVisibility(View.VISIBLE);
                    mChatInputEditLayout.setVisibility(View.VISIBLE);
                    mChatInputLayout.setVisibility(View.GONE);

                    //取得表情包
                    mActivity.get().emojController.getEmojListData(this);
                }

                break;
            case R.id.room_chat_input_edit:
                mYanView.setVisibility(View.GONE);
                break;
            case R.id.room_chat_input_check:
                if (mYanView.getVisibility() == View.VISIBLE) {
                    mYanView.setVisibility(View.GONE);
                    mChatCheck.setImageResource(R.drawable.input_smiling_face);
                    mChatInputEdit.setFocusable(true);
                    mChatInputEdit.setFocusableInTouchMode(true);
                    mChatInputEdit.requestFocus();
                    showKeyBoard();
                } else {
                    closeKeyBoard();
                    if (mHandler == null) {
                        mHandler = new Handler();
                    }
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mYanView.setVisibility(View.VISIBLE);
                            mChatCheck.setImageResource(R.drawable.keyboard);
                            mChatInputLayout.setVisibility(View.GONE);
                            mChatInputEditLayout.setVisibility(View.VISIBLE);
                            mChatInputEdit.setFocusable(true);
                            mChatInputEdit.setFocusableInTouchMode(true);
                            mChatInputEdit.requestFocus();
                        }
                    }, 300);
                }
                break;
            case R.id.room_chat_yan_send:
                if (!LedimSpUtils.isLogin()) {
                    LedimFunctionUtils.showLoginDialog(getActivity());
                } else {
                    String inputStr = mChatInputEdit.getText().toString().trim();
                    if (inputStr.length() == 0) {
                        ToastUtil.toast("请输入评论内容");
                    } else {
                        sendRoomMsg(ConstantUtil.ChatType.text, inputStr);
                        localMessage(mRoom.roomId, ConstantUtil.ChatType.text, inputStr);
                        mChatInputEdit.setText("");
                        mYanView.setVisibility(View.GONE);
                        mChatInputLayout.setVisibility(View.VISIBLE);
                        mChatInputEditLayout.setVisibility(View.GONE);
                        closeKeyBoard();
                    }
                }
                break;
            case R.id.iv_sound:
                //切换成公告输入模式
                if (mInputMode == CHAT_INPUT_MODE) {
                    mInputMode = NOTICE_INPUT_MODE;
                    showKeyBoard();
                    mChatInputLayout.setVisibility(View.GONE);
                    mChatInputEditLayout.setVisibility(View.GONE);
                }
                //myroom_input_layout.setVisibility(View.VISIBLE);
                //mChatInputLayout.setVisibility(View.GONE);
                //autoShowKeyBoard();
                break;
            case R.id.iv_switchto_keyboard:
                //切换成文字公告
                showKeyBoard();
                break;
            case R.id.iv_switchto_sound:
                //切换成语音公告
                closeKeyBoard();
                break;
            case R.id.iv_roomnoticeinput_cancle:
            case R.id.iv_roomnoticerecord_cancel:
                myroom_input_layout.setVisibility(View.GONE);
                myroom_input_edit_layout.setVisibility(View.GONE);
                mChatInputLayout.setVisibility(View.VISIBLE);
                mInputMode = CHAT_INPUT_MODE;
                closeKeyBoard();
                break;
            case R.id.ll_roomnotice_sound:
                playRecordNotice();
                break;

        }

    }

    /**
     * 播放语音公告
     */
    private void playRecordNotice() {
        if (mRoomNoticeType == NOTICE_RECORD_TYPE && !TextUtils.isEmpty(mRoomNotice)) {
            iv_palyrecord_sound.setImageResource(R.anim.playrecord_animation);
            if (mLedimRecordPlayer == null) {
                final AnimationDrawable recordPlayDrawable =
                        (AnimationDrawable) iv_palyrecord_sound.getDrawable();
                recordPlayDrawable.setOneShot(false);
                mLedimRecordPlayer =
                        new LedimRecordPlayer(new LedimRecordPlayer.LedimRecordPlayerState() {
                            @Override
                            public void onStart() {
                                recordPlayDrawable.start();
                            }

                            @Override
                            public void onComplete() {
                                iv_palyrecord_sound.setImageResource(R.drawable.sound_black_icon3);
                                recordPlayDrawable.stop();
                            }

                            @Override
                            public void onStop() {
                                recordPlayDrawable.stop();
                            }
                        });

            }
            mLedimRecordPlayer.playUrl(mRoomNotice);
        }
    }

    public void updateVideoPlay(int vid, long elapse) {
        if (mRoom != null && mRoom.status == 1) {
            if (mActivity.get() != null) {
                mActivity.get().setVid(vid, elapse);
            }
        }

    }

    @Override
    public String getTagName() {
        return FragmentConstant.TAG_FRAGMENT_ALBUM_TAB;
    }

    @Override
    public int getContainerId() {
        return R.id.play_album_tab_contain;
    }

    /**
     * 发送金币
     */
    public void sendGold(boolean isFull) {

        if (LedimNetWorkUtils.isNetworkAvailable(getActivity())) {
            if (mRoom.user != null && !TextUtils.isEmpty(mRoom.user.userId) &&
                    !mRoom.user.userId.equals(LedimSpUtils.getUid())) {
                if (mGoldCount > 0) {
                    if (mChatBearGoldBg.getVisibility() == View.GONE) {
                        mAnimationDrawable.start();
                        mChatBearGoldBg.setVisibility(View.VISIBLE);
                    }
                    if (mActivity.get() != null) {

                        if (mActivity.get()
                                     .getFullControllerFragment().mBearGoldBg.getVisibility() ==
                                View.GONE) {
                            mActivity.get()
                                     .getFullControllerFragment().mBearGoldBg.setVisibility(View.VISIBLE);
                        }
                        mPeriscopeLayout.addHeart(isFull);
                        mGoldCount -= 1;
                        mChatGoldCount.setText(LedimFunctionUtils.formatGoldCount(mGoldCount));
                        mActivity.get()
                                 .getFullControllerFragment()
                                 .setGoldCount(LedimFunctionUtils.formatGoldCount(mGoldCount));
                        mSendCount += 1;
                        mGoldHandler.removeMessages(MSG_SEND_GOLD);
                        mGoldHandler.sendEmptyMessageDelayed(MSG_SEND_GOLD, 1000);
                    }
                } else {
                    ToastUtil.toast("嘤嘤嘤，花光了");
                }
            }
        } else {
            ToastUtil.toast(R.string.net_error);
        }
    }

    /**
     * 播放上一集
     *
     * @param vid
     *         当前播放id
     */
    public void refreshLast(int vid) {

    }

    /**
     * 播放下一集
     *
     * @param vid
     *         当前播放id
     */
    public void refreshNext(int vid) {
        if (mRoom != null && mRoom.roomId != null) {
            getRoomPlayList();
        }
    }

    /**
     * 获取Room信息
     */
    public void getUserRoomInfo() {
        LedimApiServiceFactory.createService(ApiService.class).getLedimRoomInfo(mRoom.roomId)
                              .observeOn(AndroidSchedulers.mainThread())
                              .subscribeOn(Schedulers.io())
                              .subscribe(new LedimHttpObserver<RoomInfoResponse>() {

                                  @Override
                                  public void onError(Throwable e) {
                                      super.onError(e);
                                  }

                                  @Override
                                  public void onNext(RoomInfoResponse response) {
                                      LogUtil.e("ccx -- " + response.toString());
                                      if (response.success) {
                                          mRoom.status = response.data.status;
                                          mChatBean = response.ext;
                                          if (response.data.status == 0) {
                                              if (mIsMe) {
                                                  Intent intent =
                                                          new Intent(mContext, RoomActivity.class);
                                                  intent.putExtra(RoomActivity.ROOM_ID, mRoom);
                                                  intent.putExtra(RoomActivity.MY_ROOM_FLAG, mIsMe);
                                                  intent.putExtra(ConstantUtil.FROM_PUSH_MSG, mActivity
                                                          .get().mFromPushMsg);
                                                  mContext.startActivity(intent);
                                                  mActivity.get().finish();
                                                  mActivity.get()
                                                           .overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
                                              } else {
                                                  showCloseDialog();
                                              }
                                          } else {
                                              if (response.data.user != null &&
                                                      response.data.user.coin != null) {
                                                  mActivity.get()
                                                           .getFullControllerFragment()
                                                           .setUserCoin(response.data.user.coin);
                                              }

                                              if (response.ext != null &&
                                                      response.ext.history != null) {
                                                  mChatList.clear();
                                                  for (int i = 0; i < response.ext.history.size();
                                                       i++) {
                                                      LedimChatMsgBean chat =
                                                              response.ext.history.get(i);
                                                      LedimChatMsgBean msgBean =
                                                              chat.getRealChatMsgBean();
                                                      if (msgBean != null) {
                                                          addMessage(msgBean);
                                                      }
                                                  }
                                              }
                                              if (response.ext != null && mChatController != null) {
                                                  mChatController.chatConnect(response.ext.server, response.ext.chat_id);
                                              }
                                              startTimer();

                                              getRoomPlayList();

                                          }
                                      }

                                  }

                              });
    }

    /**
     * 获取播放列表
     */
    private void getRoomPlayList() {
        LedimApiServiceUtils.getRoomPlayList(mRoom.roomId, new LedimHttpObserver<RoomPlaylistResponse>() {
            @Override
            public void onError(Throwable e) {
                super.onError(e);
            }

            @Override
            public void onNext(RoomPlaylistResponse roomPlaylistResponse) {
                super.onNext(roomPlaylistResponse);
                if (roomPlaylistResponse.ext != null &&
                        roomPlaylistResponse.ext.playlist_id != null) {
                    for (int i = 0; i < roomPlaylistResponse.data.size(); i++) {
                        if (roomPlaylistResponse.ext.playlist_id.equals(roomPlaylistResponse.data.get(i).id)) {
                            updateVideoPlay(roomPlaylistResponse.data.get(i).submedia,
                                    roomPlaylistResponse.ext.elapse * 1000);
                            break;
                        }
                    }
                } else {
                    //
                    //if (roomPlaylistResponse.data.size() > 0) {
                    //    updateVideoPlay(roomPlaylistResponse.data.get(0).submedia, 0);
                    //} else {
                    //    mActivity.get().getLoadListener().noLiveVideo();
                    //}
                    showCloseDialog();
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mRoom != null && mRoom.roomId != null) {
            getUserRoomInfo();
        }
        if (LedimSpUtils.isLogin()) {
            getUserMeInfo();
        } else {
            mChatGoldCount.setVisibility(View.GONE);

        }
        if (mRoom.user != null && !TextUtils.isEmpty(mRoom.user.userId) &&
                mRoom.user.userId.equals(LedimSpUtils.getUid())) {
            mIsMe = true;
            iv_room_vedioinfo.setImageResource(R.drawable.icon_setting);
            mChatBearGold.setImageResource(R.drawable.gold_black);
        } else {
            mChatBearGold.setImageResource(R.drawable.bear_gold);
        }

    }

    private void getUserMeInfo() {
        LedimApiServiceFactory.createService(ApiService.class)
                              .getUserInfo()
                              .observeOn(AndroidSchedulers.mainThread())
                              .subscribeOn(Schedulers.io())
                              .subscribe(new LedimHttpObserver<BaseResultDataInfo<LedimUserBean>>() {

                                  @Override
                                  public void onCompleted() {
                                      super.onCompleted();
                                  }

                                  @Override
                                  public void onError(Throwable e) {
                                      super.onError(e);
                                      LogUtil.e(e.getMessage());
                                  }

                                  @Override
                                  public void onNext(BaseResultDataInfo<LedimUserBean> response) {
                                      if (response != null && response.success) {
                                          if (mIsMe) {
                                              mChatGoldCount.setVisibility(View.GONE);
                                          } else {
                                              mChatGoldCount.setVisibility(View.VISIBLE);
                                          }
                                          if (!TextUtils.isEmpty(response.data.coin)) {
                                              mGoldCount = Integer.valueOf(response.data.coin);
                                          }
                                          mChatGoldCount.setText(LedimFunctionUtils.formatGoldCount(mGoldCount));
                                          mActivity.get()
                                                   .getFullControllerFragment()
                                                   .setGoldCount(LedimFunctionUtils.formatGoldCount(mGoldCount));
                                      }
                                  }
                              });

    }

    /**
     * @param type
     * @param message
     * @param coin
     *         发送聊天消息
     */
    public void sendRoomMsg(final int type, final String message, final int coin) {

        mChatController.sendRoomMsg(mRoom.roomId, type, message, coin, new LedimHttpObserver<BaseResultDataInfo<ChatRoomBean>>() {
            @Override
            public void onCompleted() {
                super.onCompleted();
            }

            @Override
            public void onNext(BaseResultDataInfo<ChatRoomBean> data) {
                if (data.success) {
                    if (mForBiddenSpeak) {
                        localMessage(mRoom.roomId, type, message);
                        mForBiddenSpeak = false;
                    }
                } else {
                    if (data.code == 10007) {
                        mForBiddenSpeak = true;
                        //消息发送失败 被禁言了
                        showChatUserStateDialog(MessageHeader.CMD_USER_SILENT);
                    }
                }

                if (type == ConstantUtil.ChatType.coin) {
                    // 处理金币消息
                    mChatBearGold.setClickable(true);
                    if (data.success) {
                        //成功
                        if (mActivity.get() != null) {
                            mActivity.get().getFullControllerFragment().addUserCoin(coin);
                            mChatBearGold.setImageResource(R.drawable.bear_gold);
                        }

                    } else {
                        //失败
                        if (mActivity.get() != null) {
                            mGoldCount += coin;
                            mChatGoldCount.setText(LedimFunctionUtils.formatGoldCount(mGoldCount));
                            mActivity.get()
                                     .getFullControllerFragment()
                                     .setGoldCount(LedimFunctionUtils.formatGoldCount(mGoldCount));
                            mChatBearGold.setImageResource(R.drawable.bear_gold);
                        }

                    }
                }
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                mChatBearGold.setClickable(true);
                if (type == ConstantUtil.ChatType.coin) {
                    mGoldCount += coin;
                    mChatGoldCount.setText(LedimFunctionUtils.formatGoldCount(mGoldCount));
                }
            }
        });
    }

    /**
     * @param type
     * @param message
     */
    public void sendRoomMsg(int type, String message) {
        sendRoomMsg(type, message, 0);
    }

    /**
     * @param message
     */
    public void sendRoomMsg(String message) {
        if (mRoom != null && mRoom.roomId != null) {
            sendRoomMsg(ConstantUtil.ChatType.text, message);
            localMessage(mRoom.roomId, ConstantUtil.ChatType.text, message);
        }
    }

    private void addMessage(LedimChatMsgBean chat) {
        if (chat.type == ConstantUtil.ChatType.join) {
            for (int i = 0; i < mChatList.size(); i++) {
                if (!TextUtils.isEmpty(chat.user.uid) &&
                        chat.user.uid.equals(mChatList.get(i).user.uid)) {
                    return;
                }
            }
        }
        LogUtil.e("ccx addMessage :" + chat.message);
        chat.addtime = 0;
        mChatList.add(chat);
        mChatAdapter.setDatas(mChatList);
        mListView.setSelection(mChatAdapter.getCount() - 1);
        mActivity.get().getFullControllerFragment().setLocalChatMessage(chat);
    }

    /**
     * @param chat
     *         添加本地notice类型的消息
     */
    private void addNoticeMessage(LedimChatMsgBean chat) {
        LogUtil.e("ccx addMessage :" + chat.message);
        chat.addtime = 0;
        mChatList.add(chat);
        mChatAdapter.setDatas(mChatList);
        mListView.setSelection(mChatAdapter.getCount() - 1);
        mActivity.get().getFullControllerFragment().setLocalChatMessage(chat);
    }

    private void doTimeTask() {
        if (!mIsMe) {
            getRoomNoticeSubscription = LedimApiServiceFactory.createService(ApiService.class)
                                                              .getRoomNotice(mRoom.roomId)
                                                              .observeOn(AndroidSchedulers.mainThread())
                                                              .subscribeOn(Schedulers.io())
                                                              .subscribe(new LedimHttpObserver<BaseResultDataInfo<RoomNoticeBean>>() {
                                                                  @Override
                                                                  public void onCompleted() {
                                                                      super.onCompleted();
                                                                  }

                                                                  @Override
                                                                  public void onNext(
                                                                          BaseResultDataInfo<RoomNoticeBean> data) {
                                                                      if (data.success) {
                                                                          mRoomNoticeType =
                                                                                  data.data.announcement_type;
                                                                          mRoomNotice =
                                                                                  data.data.announcement;
                                                                          initRoomNoticeUi();
                                                                          LogUtil.e("getRoomNotice=== ok");
                                                                      }
                                                                  }
                                                              });
        }

        getWatchUserSubscription();
        getRoomStatus();
    }

    private void startTimer() {
        mTimer = new Timer();
        if (mTimer != null) {
            if (mHeartTimerTask != null) {
                mHeartTimerTask.cancel();
            }
            mHeartTimerTask = new HeartTimerTask();
            mTimer.schedule(mHeartTimerTask, 0, TIME);//30秒后执行，每隔30秒执行一次
        }
    }

    private void getRoomStatus() {
        LedimApiServiceFactory.createService(ApiService.class).getRoomStatus(mRoom.roomId)
                              .observeOn(AndroidSchedulers.mainThread())
                              .subscribeOn(Schedulers.io())
                              .subscribe(new LedimHttpObserver<BaseResultDataInfo<LedimRoomStatus>>() {
                                  @Override
                                  public void onCompleted() {
                                      super.onCompleted();
                                  }

                                  @Override
                                  public void onNext(BaseResultDataInfo<LedimRoomStatus> data) {
                                      mRoom.status = data.data.status;
                                      if (mRoom.status == 0) {
                                          showCloseDialog();
                                      }
                                  }

                                  @Override
                                  public void onError(Throwable e) {
                                  }
                              });
    }

    /**
     * 获取观影人头像
     */
    private void getWatchUserSubscription() {
        if (mChatBean == null) {
            return;
        }
        getWatchUserSubscription = LedimApiServiceFactory.createService(ApiService.class)
                                                         .getWatchUsers(mChatBean.chat_id, 0, 5)
                                                         .observeOn(AndroidSchedulers.mainThread())
                                                         .subscribeOn(Schedulers.io())
                                                         .subscribe(new LedimHttpObserver<BaseResultDataInfo<LedimWatchUserResponse>>() {
                                                             @Override
                                                             public void onCompleted() {
                                                                 super.onCompleted();
                                                             }

                                                             @Override
                                                             public void onError(Throwable e) {
                                                                 super.onError(e);
                                                                 LogUtil.e("ccx " +
                                                                         "getwatchuser===onError:" +
                                                                         e.getMessage());
                                                             }

                                                             @Override
                                                             public void onNext(
                                                                     BaseResultDataInfo<LedimWatchUserResponse> data) {
                                                                 if (data.success) {
                                                                     if (data.data != null &&
                                                                             data.data.list !=
                                                                                     null) {
                                                                         ll_watch_user.removeAllViews();
                                                                         for (int i = 0; i < 5;
                                                                              i++) {
                                                                             View view =
                                                                                     getActivity().getLayoutInflater()
                                                                                                  .inflate(R.layout.item_watch_users, null);
                                                                             SimpleDraweeView
                                                                                     draweeView =
                                                                                     (SimpleDraweeView) view
                                                                                             .findViewById(R.id.iv_user);
                                                                             if (i <
                                                                                     data.data.list.size()) {
                                                                                 LedimWatchUserBean
                                                                                         bean =
                                                                                         data.data.list
                                                                                                 .get(i);
                                                                                 FrescoUtil.loadUrl(bean.icon, draweeView);
                                                                             } else {
                                                                                 draweeView.setImageResource(getUserIcon());

                                                                             }
                                                                             ll_watch_user.addView(view);
                                                                         }
                                                                     }

                                                                 }
                                                             }
                                                         });
    }

    @Override
    public void onClickImage(ExpressionPackageBean image) {
        sendRoomMsg(ConstantUtil.ChatType.icon, image.url);
        localMessage(mRoom.roomId, ConstantUtil.ChatType.icon, image.url);
        mYanView.setVisibility(View.GONE);
        mChatInputEditLayout.setVisibility(View.GONE);
        mChatInputLayout.setVisibility(View.VISIBLE);
        closeKeyBoard();
    }

    @Override
    public void onGetEmjList(List<ExpressionPackageBean> datas) {
        if (!mHasInitEmojList) {
            initEmojListDataView(datas);
            mHasInitEmojList = true;
        }
    }

    @Override
    public void onGetEmjData(List<ExpressionPackageBean> emojDatas) {
        initEmojDataView(emojDatas);
    }

    @Override
    public void onYanEmojDel() {
        int selection = mChatInputEdit.getSelectionStart();
        if (selection > 0) {
            int start = EmotionHelper.replaceDel(mChatInputEdit.getText().toString(), selection);
            mChatInputEdit.getText().delete(start, selection);
        }
    }

    @Override
    public void onYanEmojInput(String s) {
        if (mChatInputEdit.getText().toString().length() < 50) {
            int start = mChatInputEdit.getSelectionStart();
            StringBuffer sb = new StringBuffer(mChatInputEdit.getText());
            sb.replace(mChatInputEdit.getSelectionStart(), mChatInputEdit.getSelectionEnd(), s);
            mChatInputEdit.setText(sb.toString());
            if (start + s.length() < 50) {
                mChatInputEdit.setSelection(start + s.length());
            }
        }
    }

    class HeartTimerTask extends TimerTask {

        @Override
        public void run() {
            doTimeTask();
        }
    }

    public void handlerChatMsg(ChatEntity chatEntity) {
        if (chatEntity.msgHead == MessageHeader.CMD_ROOM_MSG) {
            LedimChatMsgBean chat = (LedimChatMsgBean) chatEntity.data;
            if (chat.type == ConstantUtil.ChatType.coin) {
                if (!LedimSpUtils.getUid().equals(chat.uid)) {
                    int count;
                    mActivity.get().getFullControllerFragment().addUserCoin(chat.coin);
                    if (chat.coin > 10) {
                        count = 10;
                    } else {
                        count = chat.coin;
                    }
                    for (int i = 0; i < count; i++) {
                        if (UIsUtils.isLandscape(mActivity.get())) {
                            mPeriscopeLayout.addHeart(true);
                        } else {
                            mPeriscopeLayout.addHeart(false);
                        }
                    }
                }

                mChatList.add(chat);
                mChatAdapter.setDatas(mChatList);
                mListView.setSelection(mChatAdapter.getCount() - 1);
                mActivity.get().getFullControllerFragment().setLocalChatMessage(chat);
            } else {

                if (!LedimSpUtils.getUid().equals(chat.uid)) {
                    mChatList.add(chat);

                    mChatAdapter.setDatas(mChatList);
                    mListView.setSelection(mChatAdapter.getCount() - 1);

                    mActivity.get().getFullControllerFragment().setChatMessage(chat);
                } else {
                    for (int i = 0; i < mChatList.size(); i++) {
                        if (chat.timestamp == mChatList.get(i).addtime) {
                            mChatList.get(i).addtime = chat.addtime;

                            mChatAdapter.setDatas(mChatList);
                            mListView.setSelection(mChatAdapter.getCount() - 1);

                            mActivity.get().getFullControllerFragment().setChatMessage(chat);
                        }
                    }
                }
            }
        } else if (chatEntity.msgHead == MessageHeader.CMD_JOIN_ACK) {
            if (LedimSpUtils.isLogin()) {

                LedimJoinAckBean ack = (LedimJoinAckBean) chatEntity.data;
                if (ack.code == 40003) {
                    //用户已经被踢出
                    showChatUserStateDialog(MessageHeader.CMD_USER_KICKOFF);
                } else {
                    sendRoomMsg(ConstantUtil.ChatType.join, "hi" + LedimBaseUtils.randomNum());
                    localMessage(mRoom.roomId, ConstantUtil.ChatType.join, "hi");
                }
            }
        } else if (chatEntity.msgHead == MessageHeader.CMD_ROOM_USERNUMBER) {

            LedimRoomUsersInfoBean usersInfo = (LedimRoomUsersInfoBean) chatEntity.data;
            if (mRoomUserCount != usersInfo.userNum) {
                mRoomUserCount = usersInfo.userNum;
                if (getActivity() != null) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //假数据：http://wiki.letv.cn/pages/viewpage.action?pageId=53638197
                            mChatViewCount.setText((mRoomUserCount + 5) * 3 + "");
                            mChatViewCount.setVisibility(View.VISIBLE);
                            if ((mRoomUserCount + 5) * 3 > 100) {
                                mChatViewCount.setBackgroundResource(R.drawable.rect_round_room_view_count_bg);
                            } else {
                                mChatViewCount.setBackgroundResource(R.drawable.rect_round_room_view_countbig_bg);
                            }
                        }
                    });
                }
            }
            LogUtil.e("ccx usernumber=" + usersInfo.userNum + ",roomid=" + usersInfo.roomId);
        } else if (chatEntity.msgHead == MessageHeader.CMD_USER_KICKOFF ||
                chatEntity.msgHead == MessageHeader.CMD_USER_SILENT ||
                chatEntity.msgHead == MessageHeader.CMD_USER_UNSILENT) {

            LedimKickOffBean bean = (LedimKickOffBean) chatEntity.data;
            if (bean != null) {
                if (bean.uid.equals(LedimSpUtils.getLetvId())) {
                    if (chatEntity.msgHead == MessageHeader.CMD_USER_SILENT) {
                        mForBiddenSpeak = true;
                    } else if (chatEntity.msgHead == MessageHeader.CMD_USER_UNSILENT) {
                        mForBiddenSpeak = false;
                    }
                    showChatUserStateDialog(chatEntity.msgHead);
                }
                LedimChatMsgBean msgBean = new LedimChatMsgBean();
                msgBean.user = new LedimChatUserBean();
                msgBean.user.uid = bean.uid;
                msgBean.user.nickname = bean.nickname;
                msgBean.type = ConstantUtil.ChatType.notice;
                msgBean.message = getNoticeMsgByCommond(chatEntity.msgHead);
                addNoticeMessage(msgBean);
            }
        }
    }

    /**
     * @param msgCommond
     */
    private void showChatUserStateDialog(int msgCommond) {

        if (msgCommond == MessageHeader.CMD_USER_KICKOFF) {
            if (mSilentDialog != null) {
                mSilentDialog.dismiss();
            }
            if (mKickOffDialog == null) {
                mKickOffDialog =
                        CommonDialogFragment.getInstance(ConstantUtil.DialogConstant.DIALOG_VERCTIAL_TYPE, "你已被房主大大踢出该房间", "好的呢", "", new LedimDialogClickListner() {
                            @Override
                            public void onClickPositive(View view) {
                                mActivity.get().finish();
                            }

                            @Override
                            public void onClickNegative(View view) {

                            }

                            @Override
                            public void onDismiss() {

                            }
                        }, false);
            }
            if (mHandler == null) {
                mHandler = new Handler();
            }
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mActivity.get().finish();
                }
            }, 5000);
            if (!mKickOffDialog.isVisible()) {
                mKickOffDialog.showDialog(mActivity.get().getSupportFragmentManager());
            }
        } else if (msgCommond == MessageHeader.CMD_USER_SILENT) {
            if (mKickOffDialog != null) {
                mKickOffDialog.dismiss();
            }
            if (mSilentDialog == null) {
                mSilentDialog =
                        CommonDialogFragment.getInstance(ConstantUtil.DialogConstant.DIALOG_VERCTIAL_TYPE, "房主大大对你使用了禁言，你现在不能发言", "好的呢", "", new LedimDialogClickListner() {
                            @Override
                            public void onClickPositive(View view) {

                            }

                            @Override
                            public void onClickNegative(View view) {

                            }

                            @Override
                            public void onDismiss() {

                            }
                        });
            }
            if (!mSilentDialog.isVisible()) {
                mSilentDialog.showDialog(mActivity.get().getSupportFragmentManager());
            }
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        if (mHeartTimerTask != null) {
            mHeartTimerTask.cancel();
        }
        if (mChatController != null) {
            mChatController.disConnect();
        }
    }

    @Override

    public void onDestroy() {
        super.onDestroy();
        if (mTimer != null) {
            if (mHeartTimerTask != null) {
                mHeartTimerTask.cancel();
                mHeartTimerTask = null;
            }
            mTimer.cancel();
            mTimer = null;
        }

        if (subscription != null) {
            subscription.unsubscribe();
        }
        if (uploadTextSubscription != null) {
            uploadTextSubscription.unsubscribe();
        }
        if (uploadRecordSubscription != null) {
            uploadRecordSubscription.unsubscribe();
        }
        if (mLoadingBar != null) {
            mLoadingBar.dismiss();
        }
        if (getRoomNoticeSubscription != null) {
            getRoomNoticeSubscription.unsubscribe();
        }
        if (mLedimRecordPlayer != null) {
            mLedimRecordPlayer.stop();
        }
        if (getWatchUserSubscription != null) {
            getWatchUserSubscription.unsubscribe();
        }
        EventBus.getDefault().unregister(this);
        if (mAnimationDrawable != null) {
            mAnimationDrawable.stop();
        }
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        if (recordButton != null) {
            recordButton.onDestroy();
        }
        if (mBitmap != null && !mBitmap.isRecycled()) {
            mBitmap.recycle();
            mBitmap = null;
        }
    }

    // 关闭键盘
    public void closeKeyBoard() {
        if (mActivity.get() != null) {
            InputMethodManager imm = (InputMethodManager) mActivity.get()
                                                                   .getSystemService(Context.INPUT_METHOD_SERVICE);
            if (mInputMode == CHAT_INPUT_MODE) {
                mChatInputEdit.clearFocus();
                imm.hideSoftInputFromWindow(mChatInputEdit.getWindowToken(), 0);
            } else if (mInputMode == NOTICE_INPUT_MODE) {
                myroom_input_edit.clearFocus();
                imm.hideSoftInputFromWindow(myroom_input_edit.getWindowToken(), 0);
            }
        }
    }

    // 弹起键盘
    public void showKeyBoard() {
        InputMethodManager imm =
                (InputMethodManager) mActivity.get().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (mInputMode == CHAT_INPUT_MODE) {
            imm.showSoftInput(mChatInputEdit, InputMethodManager.RESULT_SHOWN);
        } else if (mInputMode == NOTICE_INPUT_MODE) {
            imm.showSoftInput(myroom_input_edit, InputMethodManager.RESULT_SHOWN);
        }

        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
    }

    /**
     * @return 是否是语C聊天室
     */
    private boolean isWucRoom() {
        return mRoom != null && mRoom.cosplay != 0;
    }

    /**
     * 本地模拟数据
     */
    private void localMessage(String roomId, int type, String message) {
        if (mForBiddenSpeak) {
            return;
        }
        String userInfo = LedimSpUtils.getUser();
        if (!TextUtils.isEmpty(userInfo)) {
            LedimUserBean user =
                    LedimGsonConverterFactory.create().gson.fromJson(userInfo, LedimUserBean.class);
            LedimChatMsgBean chat = new LedimChatMsgBean();
            chat.roomId = roomId;
            chat.message = message;
            chat.addtime = System.currentTimeMillis();
            chat.uid = LedimSpUtils.getUid();
            chat.type = type;
            LedimChatUserBean chat_user = new LedimChatUserBean();

            if (isWucRoom() && mChatBean != null &&
                    mChatBean.user_role != null) {
                if (!TextUtils.isEmpty(mChatBean.user_role.nickname)) {
                    chat_user.nickname = mChatBean.user_role.nickname;
                } else {
                    chat_user.nickname = user.nickname;
                }
                if (!TextUtils.isEmpty(mChatBean.user_role.avatar)) {
                    chat_user.icon = mChatBean.user_role.avatar;
                } else {
                    chat_user.icon = user.avatar.thumb;
                }
            } else {
                chat_user.nickname = user.nickname;
                if (user.avatar != null) {
                    chat_user.icon = user.avatar.thumb;
                }
            }
            chat_user.uid = LedimSpUtils.getLetvId();
            chat.user = chat_user;

            mChatList.add(chat);

            mChatAdapter.setDatas(mChatList);
            mListView.setSelection(mChatAdapter.getCount() - 1);

            mActivity.get().getFullControllerFragment().setLocalChatMessage(chat);
        }
    }

    private Handler mGoldHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_SEND_GOLD:
                    mChatBearGold.setClickable(false);
                    mChatBearGold.setImageResource(R.drawable.gold_black);
                    mChatBearGoldBg.setVisibility(View.GONE);
                    mAnimationDrawable.stop();
                    mActivity.get()
                             .getFullControllerFragment().mBearGoldBg.setVisibility(View.GONE);
                    sendRoomMsg(ConstantUtil.ChatType.coin,
                            "coin" + LedimBaseUtils.randomNum(), mSendCount);
                    mSendCount = 0;
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 分享
     */
    public void share(final boolean showLoadingBar) {
        if ((mBitmap == null || mBitmap.isRecycled())) {
            if (mRoom != null && mRoom.cover != null &&
                    !TextUtils.isEmpty(mRoom.cover.thumb)) {
                FrescoUtil.getBitmap(mRoom.cover.thumb, getActivity().getApplicationContext(), 0, 0, new FrescoUtil.BitmapListener() {
                    @Override
                    public void onSuccess(Bitmap bitmap, InputStream inputStream) {
                        mBitmap = bitmap.copy(bitmap.getConfig(), true);
                        LogUtil.e("ccx onSuccess");
                        if (mBitmap != null) {
                            LogUtil.e("ccx onSuccess mBitmap != null");
                            mActivity.get().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    doShare(showLoadingBar, mBitmap);
                                }
                            });
                        }

                    }

                    @Override
                    public void onFail() {
                        LogUtil.e("ccx onSuccess onFail");
                        ToastUtil.toast("系统错误，请稍后重试");
                    }
                });
            }
        } else {
            LogUtil.e("ccx onSuccess 2onFail");
            doShare(showLoadingBar, mBitmap);
        }

    }

    private void doShare(final boolean showLoadingBar, Bitmap bitmap) {
        final String shareFilePath = getShareFilePath(bitmap);
        if (TextUtils.isEmpty(shareFilePath)) {
            ToastUtil.toast("系统错误，请稍后重试");
            return;
        }
        if (TextUtils.isEmpty(shareUrl)) {
            if (mLoadingBar == null && showLoadingBar) {
                mLoadingBar = new LoadingBar(getActivity());
                mLoadingBar.show();
            }

            RequestBody photoRequestBody =
                    RequestBody.create(MediaType.parse("image/jpg"), new File(sharePath));
            subscription = LedimApiServiceFactory.createService(ApiService.class)
                                                 .getRoomShareUrl(mRoom.roomId, RequestBody.create(null, mRoom.name), photoRequestBody)
                                                 .observeOn(AndroidSchedulers.mainThread())
                                                 .subscribeOn(Schedulers.io())
                                                 .subscribe(new LedimHttpObserver<BaseResultDataInfo<ChatRoomShareData>>() {
                                                     @Override
                                                     public void onCompleted() {
                                                         super.onCompleted();
                                                     }

                                                     @Override
                                                     public void onError(Throwable e) {
                                                         super.onError(e);
                                                         LogUtil.e("onError" + e.getMessage());
                                                         if (mLoadingBar != null) {
                                                             mLoadingBar.dismiss();
                                                         }
                                                     }

                                                     @Override
                                                     public void onNext(
                                                             BaseResultDataInfo<ChatRoomShareData> data) {
                                                         super.onNext(data);
                                                         if (mLoadingBar != null) {
                                                             mLoadingBar.dismiss();
                                                         }
                                                         if (data != null && data.data != null &&
                                                                 !TextUtils.isEmpty(data.data.url) &&
                                                                 !getActivity().isFinishing()) {
                                                             shareUrl = data.data.url;
                                                             showShareDialog(shareUrl);
                                                         } else {
                                                             if (!getActivity().isFinishing()) {
                                                                 ToastUtil.toast(R.string.net_error);
                                                             }
                                                         }

                                                     }
                                                 });
        } else {

            showShareDialog(shareUrl);
        }
    }

    private String getShareFilePath(Bitmap bitmap) {
        if (TextUtils.isEmpty(sharePath)) {
            sharePath = LedimScreenShotUtils.takeScreenShot(mActivity.get(), bitmap);
        }
        if (!TextUtils.isEmpty(sharePath)) {
            File screenshot = new File(sharePath);
            if (screenshot.isFile() && screenshot.exists()) {
                return sharePath;
            }
        }
        return null;
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void showShareDialog(String shareUrl) {
        String qcode =
                LedimScreenShotUtils.videoScreenShot(mActivity.get(), mBitmap, mRootLayout);//二维码
        LogUtil.e("tabsroom showShareDialog");
        ShareDialogFragment shareDialog =
                ShareDialogFragment.getInstance(mRoom.cover.thumb, mRoom.current, mRoom.name, shareUrl, qcode);
        shareDialog.show(mActivity.get().getSupportFragmentManager(), "2");
    }

    /**
     * 房主关闭放映厅时谈框
     */
    private void showCloseDialog() {
        if (mActivity.get().getFlow() != null) {
            mActivity.get().getFlow().format();
        }
        if (mPlayEndDialog == null) {
            mPlayEndDialog =
                    CommonDialogFragment.getInstance(ConstantUtil.DialogConstant.DIALOG_HORIZONTAL_TYPE, "放映已结束,大王要去看放映厅黑历史吗？", "确定", "取消", new LedimDialogClickListner() {
                        @Override
                        public void onClickPositive(View view) {
                            Intent intent = new Intent(mContext, RoomActivity.class);
                            if (!mIsMe) {
                                mRoom.status = 0;
                            }
                            intent.putExtra(RoomActivity.ROOM_ID, mRoom);
                            intent.putExtra(RoomActivity.MY_ROOM_FLAG, mIsMe);
                            intent.putExtra(ConstantUtil.FROM_PUSH_MSG, mActivity.get().mFromPushMsg);
                            mContext.startActivity(intent);
                            mActivity.get()
                                     .overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
                        }

                        @Override
                        public void onClickNegative(View view) {
                            mActivity.get().upToHome();
                        }

                        @Override
                        public void onDismiss() {

                            mActivity.get().baseFinish();
                        }
                    }, false);
        }
        mPlayEndDialog.showDialog(getFragmentManager());
        if (mHandler == null) {
            mHandler = new Handler();
        }
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mActivity.get().finish();
            }
        }, 5000);
    }

    private boolean mHasInitEmojList;

    /**
     * @param dataList
     *         初始化表情包列表view
     */
    private void initEmojListDataView(List<ExpressionPackageBean> dataList) {
        SimpleDraweeView indexView;
        mkeyboradIndexRadioGroup.removeAllViews();
        for (int i = 0; i < dataList.size(); i++) {
            ExpressionPackageBean bean = dataList.get(i);
            indexView = new SimpleDraweeView(mActivity.get());
            indexView.setClickable(true);
            RadioGroup.LayoutParams layoutParams =
                    new RadioGroup.LayoutParams(Integer.valueOf(DensityUtil.dip2px(mActivity.get(), 40.0f)), Integer
                            .valueOf(DensityUtil.dip2px(mActivity.get(), 40.0f)));

            indexView.setPadding(20, 20, 20, 20);

            mkeyboradIndexRadioGroup.addView(indexView, layoutParams);
            FrescoUtil.loadUrl(bean.url, indexView);
            indexView.setTag(bean.package_id);
            indexView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mImageViewpager.setVisibility(View.VISIBLE);
                    mYanViewPager.setVisibility(View.GONE);
                    mActivity.get().emojController.getEmojData(String.valueOf(v.getTag()), TabsRoomFragment.this);
                }
            });
        }
    }

    /**
     * @param dataList
     *         初始化表情包View
     */
    private void initEmojDataView(List<ExpressionPackageBean> dataList) {
        List<List<ExpressionPackageBean>> mPageEmojiList =
                new ArrayList<List<ExpressionPackageBean>>();
        int pageCount = 0;
        if ((dataList.size() % 8) == 0) {
            pageCount = dataList.size() / 8;
        } else {
            pageCount = dataList.size() / 8 + 1;

        }

        //每页8个
        //判断dataList的长度
        //获取每页的数据
        for (int p = 0; p < pageCount; p++) {
            mPageEmojiList.add(getEachPageData(p, 8, dataList));
        }

        mImageViewpager.setAdapter(new EmojiPageSetAdapter(mActivity.get(), mPageEmojiList, TabsRoomFragment
                .this, false));

        mYanIndicator.setViewPager(mImageViewpager, 0);
        mYanIndicator.requestLayout();
        mImageViewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrolled(int position, float positionOffset,
                                       int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                mYanIndicator.setCurrentItem(position);

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    /**
     * 获取分页数据
     *
     * @param page
     * @return
     */
    private List<ExpressionPackageBean> getEachPageData(int page, int pageSize,
                                                        List<ExpressionPackageBean> iconList) {
        int startIndex = page * pageSize;
        int endIndex = startIndex + pageSize;
        if (endIndex > iconList.size()) {
            endIndex = iconList.size();
        }
        List<ExpressionPackageBean> list = new ArrayList<ExpressionPackageBean>();
        list.addAll(iconList.subList(startIndex, endIndex));

        return list;
    }

    public int getUserIcon() {
        Random random = new Random();
        int randomInt = random.nextInt(20);
        int value = randomInt % 5;
        switch (value) {
            case 0:
                return R.drawable.watch_user1;
            case 1:
                return R.drawable.watch_user2;
            case 2:
                return R.drawable.watch_user3;
            case 3:
                return R.drawable.watch_user4;
            default:
                return R.drawable.watch_user5;

        }

    }

    /**
     * @param msgCommond
     * @return 获取提示消息的文案
     */
    private String getNoticeMsgByCommond(int msgCommond) {
        switch (msgCommond) {
            case MessageHeader.CMD_USER_KICKOFF:
                return "被房主大大踢出了放映厅";
            case MessageHeader.CMD_USER_SILENT:
                return "被房主大大禁言了";
            case MessageHeader.CMD_USER_UNSILENT:
                return "被解除禁言了";
        }
        return null;
    }
}
